package services.frame;

import java.util.ArrayList;
import java.util.List;

import com.ani.mydragon.dto.menu.MenuObjDto;

import models.frame.*;
import org.apache.commons.lang3.StringUtils;
import org.jboss.netty.util.internal.StringUtil;
import services.exception.AniDataException;
import services.exception.AniRuleException;
import utils.HttpUtils;

public class AniFrameMenuService extends AniFrameService {

	public static List<MenuObjDto> allMenuObjects(){
		List<MenuObjDto> retMenuObjs = new ArrayList<MenuObjDto>();
		
		List<AniMenuObj> rootMenuObjs = AniMenuObj.rootMenuObjects();
		
		for(AniMenuObj oneRootMenuObj: rootMenuObjs){
			retMenuObjs.add(convertMenuObjectToDto(oneRootMenuObj));
		}
		return retMenuObjs;
	}
	
	protected static MenuObjDto convertMenuObjectToDto(AniMenuObj aniMenuObj){
		//construct url
		String url = getMenuObjectDynamicUrl(aniMenuObj);
		//construct children
		List<MenuObjDto> childrenMenuObjs = new ArrayList<MenuObjDto>();
        if(aniMenuObj.subObjects != null && !aniMenuObj.subObjects.isEmpty()){
            for(AniMenuObj oneMenuObj: aniMenuObj.subObjects){
                childrenMenuObjs.add(convertMenuObjectToDto(oneMenuObj));
            }
        }
		//construct dto
		MenuObjDto oneMenuObjDto = new MenuObjDto(
				aniMenuObj.objKey,
				url,
				childrenMenuObjs
				);
		return oneMenuObjDto;
	}
	
	protected static String getMenuObjectDynamicUrl(AniMenuObj oneObj){
		String url = "";
		try {
            if(!StringUtils.isEmpty(oneObj.controller)
                    && !StringUtils.isEmpty(oneObj.method)){
                System.out.println(oneObj.controller);
                System.out.println(oneObj.method);
                url = HttpUtils.getPlayUrlWithControllerName(
                        oneObj.controller,
                        oneObj.method);
            }
		} catch (Exception e) {
			throw new AniDataException("GET_MENU_OBJECT_URL_FAILED");
		}
		return url;
	}
}
